package com.chat.handler;

import com.chat.model.ChatMessage;
import com.chat.service.ChatService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * WebSocket消息处理器
 * 处理WebSocket连接的建立、消息接收、连接关闭等事件
 */
@Component
public class ChatWebSocketHandler implements WebSocketHandler {

    private static final Logger logger = Logger.getLogger(ChatWebSocketHandler.class.getName());
    
    @Autowired
    private ChatService chatService;
    
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * WebSocket连接建立后调用
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("WebSocket连接已建立: " + session.getId());
        System.out.println("连接来源: " + session.getRemoteAddress());
        System.out.println("连接URI: " + session.getUri());
        chatService.addSession(session);
    }

    /**
     * 接收到WebSocket消息时调用
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        if (message instanceof TextMessage) {
            String payload = ((TextMessage) message).getPayload();
            logger.info("收到消息: " + payload);
            
            try {
                // 解析JSON消息
                ChatMessage chatMessage = objectMapper.readValue(payload, ChatMessage.class);
                
                // 根据消息类型处理
                switch (chatMessage.getType()) {
                    case "JOIN":
                        chatService.handleUserJoin(session, chatMessage.getUsername());
                        break;
                    case "CHAT":
                        chatService.handleChatMessage(session, chatMessage);
                        break;
                    case "LEAVE":
                        chatService.handleUserLeave(session);
                        break;
                    default:
                        logger.warning("未知消息类型: " + chatMessage.getType());
                }
            } catch (Exception e) {
                logger.severe("处理消息时发生错误: " + e.getMessage());
                sendErrorMessage(session, "消息格式错误");
            }
        }
    }

    /**
     * WebSocket传输错误时调用
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.err.println("WebSocket传输错误: " + session.getId() + ", 错误: " + exception.getMessage());
        System.err.println("错误类型: " + exception.getClass().getSimpleName());
        System.err.println("会话状态: " + (session.isOpen() ? "开启" : "关闭"));
        exception.printStackTrace();
    }

    /**
     * WebSocket连接关闭后调用
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.info("WebSocket连接关闭: " + session.getId() + ", 状态: " + closeStatus.toString());
        // 处理用户离开
        chatService.handleUserLeave(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 发送错误消息给客户端
     */
    private void sendErrorMessage(WebSocketSession session, String errorMsg) {
        try {
            ChatMessage errorMessage = new ChatMessage();
            errorMessage.setType("ERROR");
            errorMessage.setMessage(errorMsg);
            errorMessage.setTimestamp(java.time.Instant.now());
            
            String json = objectMapper.writeValueAsString(errorMessage);
            session.sendMessage(new TextMessage(json));
        } catch (IOException e) {
            logger.severe("发送错误消息失败: " + e.getMessage());
        }
    }
}